package com.doubao.user.controller;

import com.doubao.common.result.Result;
import com.doubao.user.dto.MembershipOrderDTO;
import com.doubao.user.dto.request.SubscriptionRequestDTO;
import com.doubao.user.service.MembershipSubscriptionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 会员订阅控制器
 */
@RestController
@RequestMapping("/user/membership")
@RequiredArgsConstructor
@Tag(name = "会员订阅", description = "会员订阅相关接口")
@Slf4j
public class MembershipSubscriptionController {

    private final MembershipSubscriptionService subscriptionService;

    @PostMapping("/subscribe")
    @Operation(summary = "创建会员订阅订单", description = "创建会员订阅支付订单")
    public Result<MembershipOrderDTO> createSubscriptionOrder(
            @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @RequestBody SubscriptionRequestDTO subscriptionRequest,
            HttpServletRequest request) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }

        Integer levelId = subscriptionRequest.getLevelId();
        String subscriptionType = subscriptionRequest.getSubscriptionType();
        
        String clientIp = subscriptionRequest.getClientIp();
        if (clientIp == null || clientIp.isEmpty()) {
            clientIp = getClientIp(request); 
        } else {
             log.info("使用前端传入的IP地址: {}", clientIp);
        }
        
        if (levelId == null || subscriptionType == null || subscriptionType.isEmpty()) {
            return Result.failed("缺少必要的订阅参数：levelId 或 subscriptionType");
        }

        return subscriptionService.createSubscriptionOrder(userId, levelId, subscriptionType, clientIp);
    }

    @GetMapping("/order/{orderId}")
    @Operation(summary = "获取订阅订单", description = "获取会员订阅订单详情")
    public Result<MembershipOrderDTO> getSubscriptionOrder(
        @RequestHeader(value = "X-User-ID", required = false) Long userId,
        @PathVariable String orderId) {
         if (userId == null) {
            return Result.failed("用户未登录");
        }
        return subscriptionService.getSubscriptionOrder(orderId);
    }

    // 添加一个新的端点，路径更明确
    @GetMapping("/order/query/{orderId}")
    @Operation(summary = "查询订阅订单", description = "查询会员订阅订单详情")
    public Result<MembershipOrderDTO> querySubscriptionOrder(
            @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @PathVariable String orderId) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }
        return subscriptionService.getSubscriptionOrder(orderId);
    }


    @PostMapping("/subscription/cancel")
    @Operation(summary = "取消会员订阅", description = "取消当前用户的会员订阅")
    public Result<Void> cancelSubscription(@RequestHeader(value = "X-User-ID", required = false) Long userId) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }
        return subscriptionService.cancelSubscription(userId);
    }

    @PostMapping("/subscription/renew")
    @Operation(summary = "续订会员", description = "续订当前用户的会员")
    public Result<MembershipOrderDTO> renewSubscription(
            @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @RequestBody SubscriptionRequestDTO subscriptionRequest,
            HttpServletRequest request) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }

        String subscriptionType = subscriptionRequest.getSubscriptionType();
        String clientIp = subscriptionRequest.getClientIp();
        if (clientIp == null || clientIp.isEmpty()) {
            clientIp = getClientIp(request);
        }
        
        if (subscriptionType == null || subscriptionType.isEmpty()) {
             return Result.failed("缺少必要的续订参数：subscriptionType");
        }

        return subscriptionService.renewSubscription(userId, subscriptionType, clientIp);
    }

    @PostMapping("/payment-success/{orderId}")
    @Operation(summary = "处理支付成功回调", description = "处理会员订阅支付成功回调")
    public Result<Void> handlePaymentSuccess(
            @PathVariable String orderId,
            @RequestParam(required = false) String transactionId) {
        
        log.info("【会员订阅】处理支付成功回调: orderId={}, transactionId={}", 
                orderId, transactionId);
        
        try {
            // 检查基本参数
            if (orderId == null || orderId.isEmpty()) {
                log.error("【会员订阅】订单ID为空");
                return Result.failed("订单ID不能为空");
            }

            log.info("【会员订阅】开始调用订阅服务处理支付成功回调");
            // 调用订阅服务处理支付成功逻辑
            Result<Void> result = subscriptionService.handleSubscriptionPaySuccess(orderId);
            
            if (result.isSuccess()) {
                log.info("【会员订阅】支付成功回调处理完成: orderId={}", orderId);
            } else {
                log.error("【会员订阅】支付成功回调处理失败: orderId={}, 错误={}", orderId, result.getMessage());
            }
            
            return result;
        } catch (Exception e) {
            log.error("【会员订阅】处理支付成功回调异常: orderId={}, error={}", orderId, e.getMessage(), e);
            return Result.failed("处理支付回调异常: " + e.getMessage());
        }
    }

    /**
     * 处理支付成功回调 - JSON版本
     * 接收JSON格式的请求体，解决前端请求格式问题
     */
    @PostMapping("/payment-callback/{orderId}")
    @Operation(summary = "处理支付成功回调(JSON)", description = "处理会员订阅支付成功回调，接收JSON格式请求")
    public Result<Void> handlePaymentCallback(
            @PathVariable String orderId,
            @RequestBody(required = false) Map<String, Object> requestBody) {
        
        log.info("【会员订阅-JSON】处理支付成功回调: orderId={}, requestBody={}", 
                orderId, requestBody);
        
        String transactionId = null;
        if (requestBody != null && requestBody.containsKey("transactionId")) {
            transactionId = (String) requestBody.get("transactionId");
        }
        
        try {
            // 检查基本参数
            if (orderId == null || orderId.isEmpty()) {
                log.error("【会员订阅-JSON】订单ID为空");
                return Result.failed("订单ID不能为空");
            }

            log.info("【会员订阅-JSON】开始调用订阅服务处理支付成功回调");
            // 调用订阅服务处理支付成功逻辑
            Result<Void> result = subscriptionService.handleSubscriptionPaySuccess(orderId);
            
            if (result.isSuccess()) {
                log.info("【会员订阅-JSON】支付成功回调处理完成: orderId={}", orderId);
            } else {
                log.error("【会员订阅-JSON】支付成功回调处理失败: orderId={}, 错误={}", orderId, result.getMessage());
            }
            
            return result;
        } catch (Exception e) {
            log.error("【会员订阅-JSON】处理支付成功回调异常: orderId={}, error={}", orderId, e.getMessage(), e);
            return Result.failed("处理支付回调异常: " + e.getMessage());
        }
    }

    /**
     * 获取客户端真实IP
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }
}